package cn.wolfcode.wolf2w.redis.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.IUserInfoRedisService;
import cn.wolfcode.wolf2w.util.AssertUtil;
import cn.wolfcode.wolf2w.util.RedisKeys;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static cn.wolfcode.wolf2w.util.RedisKeys.LOGIN_TOKEN;
import static cn.wolfcode.wolf2w.util.RedisKeys.VERIFY_CODE;

@Service
public class UserInfoRedisServiceImpl implements IUserInfoRedisService {

    // 项目规定了 key value 的类型都为 String
    @Autowired
    private StringRedisTemplate template;

    @Override
    public void saveCode(String phone, String code) {
        // 设计key：1.唯一   2.可读    3.失效    4.灵活
        String verifyCode = VERIFY_CODE.join(phone);
        template.opsForValue().set(verifyCode, code, VERIFY_CODE.getTime(), TimeUnit.SECONDS);
    }

    @Override
    public String getCode(String key) {
         return template.opsForValue().get(key);
    }

    @Override
    public void addToken(String token, String user) {
        // 为了可读性，给token添加个前缀
        String key = LOGIN_TOKEN.join(token);
        template.opsForValue().set(key,user,LOGIN_TOKEN.getTime(),TimeUnit.SECONDS);
    }

    @Override
    public UserInfo getUserByToken(String token) {
        // 判断token
        if (!StringUtils.hasLength(token)){
            return null;
        }
        // 通过token 获取到users对象
        String key = LOGIN_TOKEN.join(token);
        String userInfo = template.opsForValue().get(key);
        // 如果存在，转换为user对象，返回这个user对象
        if (userInfo != null){
            UserInfo user = JSON.parseObject(userInfo, UserInfo.class);
            // 重置时间
            template.expire(key, LOGIN_TOKEN.getTime(), TimeUnit.SECONDS);
            return user;
        }
        return null;
    }

    @Override
    public List<String> queryStrategyFavorListByUid(String uid) {
        String key = RedisKeys.STRATEGY_STATIS_FAVORNUM.join(uid);
        String s = template.opsForValue().get(key);
        List<String> sidList = JSON.parseArray(s, String.class);
        return sidList;
    }

}
